from google.appengine.ext import db, webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import simplejson as json
import models
import base64

class GetAll(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        dishes = db.GqlQuery("SELECT * from Dish")
        result = [{'key': str(dish.key()), 'name': str(dish.name)} for dish in dishes]
        self.response.out.write(json.dumps(result))

class GetKeyByName(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write("in GET");
            
    def post(self):
        self.response.headers['Content-Type'] = 'text/plain'
        dishName = self.request.get("dishName");
        query = db.GqlQuery("SELECT __key__ FROM Dish WHERE name = :1 LIMIT 1", dishName);
        if query.count(1) != 0:
            self.response.out.write(query[0]);
        else:
            self.response.out.write("Not found");
            
class CreateDish(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write("in GET");
            
    def post(self):
        self.response.headers['Content-Type'] = 'text/plain'
        dishName = self.request.get("dishName");
        dishTypeName = self.request.get("dishType");
        ingredientsString = self.request.get("ingredients");
        dishRatingString = self.request.get("dishRating");
        dishImageBase64 = self.request.get("dishImage");
        restaurantName = self.request.get("restaurantName");
        isNewRestaurant = self.request.get("isNewRestaurant");
        longitudesString = self.request.get("longitudes");
        latitudesString = self.request.get("latitudes");
        
        longitudes = []
        longitudesSplit = longitudesString.split('#');
        for longitude in longitudesSplit:
            longitudes.append(float(longitude)); 

        latitudes = []
        latitudesSplit = latitudesString.split('#');          
        for latitude in latitudesSplit:
            latitudes.append(float(latitude));
        
        dishRestaurant = None;
        if isNewRestaurant == "no":      
            query = db.GqlQuery("SELECT * FROM Restaurant WHERE name = :1 LIMIT 1", restaurantName);
            dishRestaurant = query[0];
            dishRestaurant.locationLong.extend(longitudes);
            dishRestaurant.locationLat.extend(latitudes);
        else:
            dishRestaurant = models.Restaurant(name=restaurantName, locationLong=longitudes, locationLat=latitudes);
        dishRestaurant.put();
        
        dishTypeQuery = db.GqlQuery("SELECT * FROM DishType WHERE name = :1 LIMIT 1", dishTypeName);
        
        dishRating = int(float(dishRatingString));
        numRating = 0;
        avRating = 0;
        if dishRating != 0:
            avRating = dishRating;
            numRating = 1;
            
        
        dishImageBinary = base64.decodestring(dishImageBase64);
        
        dishIngredients = []
        if len(ingredientsString) > 2:
            ingredientsSub = ingredientsString[1:-1]
            ingredientsList = ingredientsSub.split(', ')
            for ingredient in ingredientsList:
                query = db.GqlQuery("SELECT __key__ FROM Ingredient WHERE name = :1 LIMIT 1", ingredient.strip());
                dishIngredients.append(query[0]);
        
        dish = models.Dish(name=dishName, img=db.Blob(dishImageBinary), av_rate=avRating, no_rate=numRating, dishType=dishTypeQuery[0], ingredients=dishIngredients, restaurant=dishRestaurant.key());
        dish.put();
                
application = webapp.WSGIApplication([('/dishes/all', GetAll), ('/dishes/get_key', GetKeyByName), ('/dishes/new', CreateDish)], debug=True)
  
def main():
    run_wsgi_app(application)
    
if __name__ == "__main__":
    main()
